﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.Web.IntelligentQuery.Model;

namespace Seven.Web.IntelligentQuery.Extensions
{
    public static class QueryModelExtensions
    {
        /// <summary>
        /// 添加查询条件
        /// </summary>
        /// <param name="model">查询条件数据模型</param>
        /// <param name="key">字段</param>
        /// <param name="val">值</param>
        public static void AddQueryItem(this QueryModel model, string key, string val)
        {
            string field = "", prefix = "", method = "";
            var keywords = key.Split(new char[] { MvcHtmlStringExtensions.methodPostfix, MvcHtmlStringExtensions.prefixPostfix }, 3);
            //将Html中的name分割为我们想要的几个部分
            foreach (var keyword in keywords)
            {
                if (Char.IsLetterOrDigit(keyword[0])) { field = keyword; continue; }
                var last = keyword.Substring(1);
                if (keyword[0] == MvcHtmlStringExtensions.prefixPrefix) { prefix = last; }
                else if (keyword[0] == MvcHtmlStringExtensions.methodPrefix) { method = last; }
            }
            if (string.IsNullOrEmpty(method)) { return; }
            if (!string.IsNullOrEmpty(field))
            {
                var item = new ConditionItem
                {
                    Field = field,
                    Value = val.Trim(),
                    Prefix = prefix,
                    Method = (QueryMethod)Enum.Parse(typeof(QueryMethod), method)
                };
                model.Items.Add(item);
            }
        }
    }
}
